package com.leedsoft.common;

import java.util.Map;

/**
 * 统一格式的ajax请求的数据返回接口
 * json格式：
 * {
 * status: 0,
 * code: 0,
 * msg: "",
 * data: object/list
 * }
 * status: 0,表示请求成功。1表示异常。
 * code 返回码
 *    返回码约定：
 *      1、三位数字
 *      2、2XX是status为0请求成功后的返回码。
 *      3、300是异常默认返回码
 *      4、4XX是客户端异常返回码，通常是由于客户端非法操作导致的异常，例如非法传参
 *      5、5XX是服务端异常返回码，表示服务端出错。
 * msg 返回说明
 * data为具体返回的数据。
 * Created by leeds on 2017/6/19 15:46.
 */
public class AjaxReply {
//    private static final int DEFAULT_SUCCESS_CODE = 200;
    private static final int DEFAULT_ERROR_CODE = 300;
    enum Status {
        SUCCESS(0), ERROR(1);
        private Integer code;
        Status(Integer code) {
            this.code = code;
        }

        public Integer getCode() {
            return code;
        }
    }


    private static class Tpl<T> {
        private Integer status = 0;
        private Integer code = 0;
        private String msg = "";
        private T data;

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public T getData() {
            return data;
        }

        public void setData(T data) {
            this.data = data;
        }

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public Map<String, Object> toJson() {
            return JSON.gson.fromJson(JSON.gson.toJson(this), Map.class);
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }
    }

    public static Map<String, Object> err(String errmsg) {
        return err(errmsg, DEFAULT_ERROR_CODE, null);
    }

    public static Map<String, Object> err(String errmsg, Integer code) {
        return err(errmsg, code, null);
    }

    public static <T> Map<String, Object> err(String errmsg, Integer code, T data) {
        Tpl tpl = new Tpl();
        tpl.setStatus(Status.ERROR.getCode());
        tpl.setCode(code);
        tpl.setMsg(errmsg);
        tpl.setData(data);
        return tpl.toJson();
    }

    public static Map<String, Object> success() {
        return success(null);
    }

    public static <T> Map<String, Object> success(T t) {
        return success(t, 0);
    }

    public static <T> Map<String, Object> success(T t, Integer code) {
        return success(t, code, "");
    }

    public static <T> Map<String, Object> success(T t, Integer code, String msg) {
        Tpl tpl = new Tpl();
        tpl.setStatus(Status.SUCCESS.getCode());
        tpl.setData(t);
        tpl.setCode(code);
        tpl.setMsg(msg);
        return tpl.toJson();
    }

}
